package com.blog.websocket;// NotificationWebSocket.java
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

@ServerEndpoint("/websocket/notification/{userId}")
public class NotificationWebSocket {
    // 存储所有连接的用户
    private static Map<String, Session> userSessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        userSessions.put(userId, session);
        System.out.println("user " + userId + " connected");
    }
    
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        userSessions.remove(userId);
        System.out.println("user " + userId + " disconnect");
    }
    
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }
    
    // 发送通知给指定用户
    public static void sendNotification(String userId, NotificationMessage message) {
        Session session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                String json = JSONUtil.toJsonStr( message);
                session.getBasicRemote().sendText(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    // 通知消息类
    public static class NotificationMessage {
        private String type;
        private String title;
        private String content;
        private String articleId;
        private String commenter;
        
        // 构造函数
        public NotificationMessage() {}
        
        public NotificationMessage(String type, String title, String content, String articleId, String commenter) {
            this.type = type;
            this.title = title;
            this.content = content;
            this.articleId = articleId;
            this.commenter = commenter;
        }
        
        // Getters and Setters
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        
        public String getArticleId() { return articleId; }
        public void setArticleId(String articleId) { this.articleId = articleId; }
        
        public String getCommenter() { return commenter; }
        public void setCommenter(String commenter) { this.commenter = commenter; }
    }
}
